package app_kvEcs;

import infrastructure.DataReader;
import infrastructure.ExceptionHandler;
import infrastructure.LoggingManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import client.Commands;

public class ECSClient implements Runnable {

	private Logger logger = LoggingManager.CreateEcsLogger(ECSClient.class);
	private boolean isRunning;
	private String CONSOLE_MESSAGE = "ECS>";
	private IECS ecs;
	private String configurationFileName = "ecs.config";
	
	public ECSClient (String configurationFileName, String separator, String scriptFile) throws Exception {
		this.configurationFileName = configurationFileName;
		DataReader dataReader = new DataReader(configurationFileName, separator);		
		ecs = new ECS(dataReader.getData(), scriptFile);
	}
		
	
	@Override
	public void run() {
		logger.info("Starting ECS");
		Println("Welcome to ECS Danielondon. Version 1.0.");		
		this.isRunning = true;
		// Console Application. Read Option of the User
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));		
		logger.debug("Input Stream Reader created");
		Print(CONSOLE_MESSAGE);
		while (this.isRunning)
		{	
			try{
				String inputOption = input.readLine();
				logger.info(inputOption);
				handleInputUser(inputOption);				
			}catch(Exception ex){
				logger.error(ex);
				ExceptionHandler.Handle(ex);
			}	
			
			if (this.isRunning)
				Print(CONSOLE_MESSAGE);
		}	
		
		// Tear down the server.
		try{
			ecs.shutDown();
		}catch(Exception ex){
			logger.error("ECS fails shutting down.");
		}
		
		Println("Exiting ECS");
		logger.info("ECS closed.");
	}
	
	private void handleInputUser(String inputOption) throws Exception {
		String[] tokens = inputOption.trim().split("\\s");
		if(tokens.length > 0) {
			String command = tokens[0].toLowerCase();
			logger.info("Input command " + command);
			
			if(command.compareTo(CommandsECS.INIT) == 0){
				int amount = 0;
				try {
					amount = Integer.parseInt(tokens[1]);
				} catch (Exception ex) {
					Println("Incorrect parameters for " + command);
					return;
				}
				
				if (!this.ecs.initServer(amount))
					Println("Server was not initiated");
			}
			else if(command.compareTo(CommandsECS.START) == 0){
				this.ecs.start();				
			}			
			else if(command.compareTo(CommandsECS.STOP) == 0){
				this.ecs.stop();
			} else if(command.compareTo(CommandsECS.SHUTDOWN) == 0){				
				this.ecs.shutDown();
			}
			else if(command.compareTo(CommandsECS.ADD) == 0){				
				this.ecs.addNode();
			} 
			else if(command.compareTo(CommandsECS.REMOVE) == 0){				
				this.ecs.removeNode();
			}
			else if(command.compareTo(CommandsECS.HELP) == 0){
				Println("This is your ECS application.");
				PrintHelp();
			}
			else if(command.compareTo(CommandsECS.LOG_LEVEL) == 0){
				setLogLevel(tokens);
			}
			else if(command.compareTo(Commands.QUIT) == 0){
				this.isRunning = false;		
			}
			else
			{
				Println("Unknown Command");
				PrintHelp();
			}
		}
	}

	private void setLogLevel(String[] tokens) {
		if ( tokens.length == 1 ){
			Println(String.format("Log Level %s", logger.getLevel()));
		} else if ( tokens.length == 2 ){
			LoggingManager.SetLoggerLevel(tokens[1]);							
			Println(String.format("New Log Level is %s", logger.getLevel()));
		} else {
			Println("Incorrect amount of parameters");
		}
	}

	public void Print(String message){
		System.out.print(message);
	}
	
	public void Println(String message){
		System.out.println(message);
	}

	public void PrintHelp()
	{		
		Println("The following are the commands available:");
		Println("   " + CommandsECS.INIT  );
		Println("   " + CommandsECS.START );
		Println("   " + CommandsECS.STOP );
		Println("   " + CommandsECS.SHUTDOWN );
		Println("   " + CommandsECS.ADD );
		Println("   " + CommandsECS.REMOVE );
		Println("   " + CommandsECS.HELP);
		Println("   " + CommandsECS.LOG_LEVEL + "[<New Log Level to set>]");		
		Println("   " + CommandsECS.QUIT);
	}
	
	
	public static void main(String []  args) {
		String configFile = "ecs.config";
		String scriptFile = "script.sh";
		if (args.length > 0)
			configFile = args[0];
		if (args.length > 1)
			scriptFile = args[1];
		String separator = " ";
		
		try {
			new ECSClient(configFile, separator, scriptFile).run();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		/*Process proc;
		String script = "./script.sh";
		 
		Runtime run = Runtime.getRuntime();
		try {
		   proc = run.exec(script);
		} catch (IOException e) {
		   e.printStackTrace();
		}		
	}*/
}
